use std::ops::{Add, Sub};
use chrono::{Datelike, Duration, Month};
use crate::DayItem;

pub fn get_month_days(year: i32, month: u32) -> Vec<Vec<DayItem>> {
    let total_days = 35u32;
    let current_year = year;
    let current_month = month;
    let mut first_day = chrono::NaiveDate::from_ymd_opt(current_year, current_month, 1).unwrap();
    let mut first_day_of_month = first_day.clone();
    let week_day = first_day.clone().weekday().num_days_from_monday();
    let first_day_of_next_month = if (current_month == 12) {
        let next_year = current_year + 1;
        let next_month = 1u32;
        chrono::NaiveDate::from_ymd_opt(next_year, next_month, 1).unwrap()
    } else {
        first_day.clone().with_month(current_month + 1).unwrap()
    };
    // 生成从第一天到下个月第一天前一天的日期列表
    let mut days = vec![];
    while first_day < first_day_of_next_month {
        days.push(first_day.format("%Y-%m-%d").to_string());
        first_day = first_day.add(Duration::days(1));
    }

    for i in 0..week_day {
        if (days.len() as u32 == total_days) {
            break;
        }
        let pre_day = first_day_of_month.clone().sub(Duration::days(i as i64));
        days.insert(0, pre_day.format("%Y-%m-%d").to_string());
    }
    let days_count = days.len() as u32;
    for i in 0..(total_days - days_count) {
        days.push(first_day.format("%Y-%m-%d").to_string());
        first_day = first_day.add(Duration::days(1));
    }

    let mut days_vec = vec![];
    let mut temp_days = vec![];
    for (index, item) in days.iter().enumerate() {
        temp_days.push(DayItem {
            day: item.to_string(),
            color: "".to_string(),
        });
        if index != 0 && (index + 1) % 7 == 0 {
            days_vec.push(temp_days);
            temp_days = vec![];
        }
    }
    if !temp_days.is_empty() {
        days_vec.push(temp_days);
    }
    println!("days: {:?}", days);
    days_vec
}